/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.ubhave.sensormanager.ability;

import com.ubhave.sensormanager.*;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.push.PhoneStateData;
import com.ubhave.sensormanager.sensors.SensorUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.bundle.IBundleManager;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;

import java.util.Optional;

public class PhoneStateAbility extends Ability implements SensorDataListener, Component.ClickedListener {

    private Text phoneState;
    private Button startBtn;
    private Button stopBtn;
    private ESSensorManager sensorManager;
    private int subscriptionId;
    private String[] permissions = new String[]{ "ohos.permission.PLACE_CALL" ,"ohos.permission.GET_TELEPHONY_STATE","ohos.permission.LOCATION"};//"ohos.permission.PLACE_CALL" ,"ohos.permission.GET_TELEPHONY_STATE","ohos.permission.LOCATION"
    private SensorData mSensorData;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_phone_state);
        startBtn = (Button) findComponentById(ResourceTable.Id_start_btn);
        stopBtn = (Button) findComponentById(ResourceTable.Id_stop_btn);
        phoneState = (Text) findComponentById(ResourceTable.Id_data_phone_state);
        startBtn.setClickedListener(this);
        stopBtn.setClickedListener(this);
        requestPermissions();
    }

    private void requestPermissions() {
        for (String permission : permissions) {
            if (verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                // 应用未被授予权限
//                if (canRequestPermission(permission)) {
                    // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                    requestPermissionsFromUser(
                            permissions, 1001);
//                } else {
//                    // 显示应用需要权限的理由，提示用户进入设置授权
//                }
            } else {
                // 权限已被授予
                System.out.println("已授权");
            }
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1001: {
                // 匹配requestPermissions的requestCode
                if (grantResults.length > 0
                        && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    // 权限被授予
                    // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
                    System.out.println("已授权");
                } else {
                    // 权限被拒绝
                }
                break;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {
            try {
                sensorManager.unsubscribeFromSensorData(subscriptionId);
            } catch (ESException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDataSensed(SensorData data) {
        mSensorData = data;
        parseData(mSensorData);

    }

    private void parseData(SensorData data) {
        if (!(data instanceof PhoneStateData)) {
            return;
        }
        getContext().getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override
            public void run() {
                PhoneStateData phoneStateData = (PhoneStateData) data;
                StringBuffer buffer = new StringBuffer();
                final String number = phoneStateData.getNumber();
                final String data1 = phoneStateData.getData();
                buffer.append("number: ");
                buffer.append(number);
                buffer.append("\n");
                buffer.append("data");
                buffer.append(data1);
                phoneState.setText(buffer.toString());
            }
        });
    }

    @Override
    public void onCrossingLowBatteryThreshold(boolean isBelowThreshold) {

    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_start_btn:
                try {
                    sensorManager = ESSensorManager.getSensorManager(getContext());
                    subscriptionId = sensorManager.subscribeToSensorData(SensorUtils.SENSOR_TYPE_PHONE_STATE, this);
                } catch (ESException e) {
                    e.printStackTrace();
                }
                break;
            case ResourceTable.Id_stop_btn:
                if (sensorManager != null) {
                    try {
                        sensorManager.unsubscribeFromSensorData(subscriptionId);
                    } catch (ESException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        Optional<Sequenceable> sensorDataOptional = inState.getSequenceable("sensorData");
        if(sensorDataOptional.isPresent()) {
            mSensorData = (SensorData) sensorDataOptional.get();
            parseData(mSensorData);
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        if(mSensorData != null) {
            outState.putSequenceableObject("sensorData", mSensorData);
        }
    }
}
